layui.define(['index', 'form', 'table', 'laypage', 'layedit'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;

    zmnLayUtil.layFormVerify(form);

    form.on('submit(zmn-form-submit)', function (obj) {
        let allSelectedCheckbox = $("input[name='areaId']:checkbox:checked");

        if (allSelectedCheckbox.length <= 0) {
            layer.msg("城市必选，请调整后再试！", {icon: 2});
            return false;
        }

        let data = new Array();
        allSelectedCheckbox.each(function () {
            let value = $(this).val();
            let valueArr = value.split("-");
            let innerObject = new Object();
            innerObject['groupId'] = json.groupId;
            innerObject['provinceId'] = valueArr[0];
            innerObject['cityId'] = valueArr[1];
            data.push(innerObject);
        });

        var url = "/online/service/group/city/configCity.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success:function(resp) {
                if(resp.status == 200) {
                    zmnPage.reload(resp.message, 1000);
                } else {
                    layer.open({
                        title: '温馨提示'
                        ,content: resp.message
                    });
                }
            },
            error:function(XMLHttpRequest, status, errorThrown){}
        });

    });

    form.on('checkbox(checkAll)', function(data){
        var _class = data.value;
        if (data.elem.checked) {
            $("." + _class).each(function(){
                $(this).prop("checked",true);
            });
            form.render('checkbox');
        } else {
            $("." + _class).each(function(){
                $(this).prop("checked",false);
            });
            form.render('checkbox');
        }
        form.render('checkbox');
    });

    var checkAll = function (data) {
        var _class = data.value.substr(0, data.value.lastIndexOf("-"));
        var item = $("." + _class);
        for (var i = 0; i < item.length; i++) {
            if (item[i].checked == false) {
                $("input[value='"+_class+"'").prop("checked", false);
                form.render('checkbox');
                return;
            }
        }
        //如果都勾选了  勾上全选
        var all = item.length;
        for (var i = 0; i < item.length; i++) {
            if (item[i].checked == true) {
                all--;
            }
        }
        if(all == 0){
            $("input[value='"+_class+"'").prop("checked", true);
            form.render('checkbox');
        }
    };

    //有一个未选中全选取消选中
    form.on('checkbox(checkOne)', checkAll);

    $(".checkAll").each(function(){
        checkAll({value : this.value + "-0"});
    })

    //对外暴露的接口
    exports('online_service_group_city_js', {});
});
